/**
 *
 * @author GG
 */
package com.wzhq.pacsai;

import com.wzhq.commTencent.PostTencent;
import com.wzhq.util.Sha256;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.UUID;
import java.util.logging.Level;

import org.dcm4che3.data.Attributes;
import org.dcm4che3.data.DatasetWithFMI;
import org.dcm4che3.data.Tag;
import org.dcm4che3.data.VR;
import org.dcm4che3.io.DicomInputStream;
import org.dcm4che3.io.DicomOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DicomUtil {

    private static final Logger LOG = LoggerFactory.getLogger(DicomUtil.class);
    private DicomInputStream dis = null;

    private DatasetWithFMI datasetWithFMI = null;

    private Attributes data = null;

    private Attributes fmi = null;

    public DicomUtil() {
    }

    public DicomUtil(InputStream is, int type) {
        super();
        try {
            dis = new DicomInputStream(is);
            datasetWithFMI = dis.readDatasetWithFMI();
            data = datasetWithFMI.getDataset();
            fmi = datasetWithFMI.getFileMetaInformation();
            dis.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public DicomUtil(File dicom) {
        //File dicom = new File("C:\\aaa\\1.2.840.113704.1.111.2064.1516586961.450");
        InputStream fis;
        try {
            fis = new FileInputStream(dicom);
            try {
                dis = new DicomInputStream(fis);
                datasetWithFMI = dis.readDatasetWithFMI();
                data = datasetWithFMI.getDataset();
                fmi = datasetWithFMI.getFileMetaInformation();
                dis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                fis.close();
                PostTencent.ERRDCMOPERFLAG = 1;
                LOG.warn("解析DICOM文件Can not find files!", dicom);
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            PostTencent.ERRDCMOPERFLAG = 1;
            LOG.warn("解析DICOM文件Can not find files!", dicom);
            e.printStackTrace();
        } catch (IOException e) {
            PostTencent.ERRDCMOPERFLAG = 1;
            LOG.warn("解析DICOM文件 read in dicom file failed!", dicom);
            e.printStackTrace();
        }
    }

    public String getValueByTag(int tag) {
        String value = "";
        if (data != null) {
            value = data.getString(tag);
        }
        return value;
    }

    public void setValueByTag(int tag, VR vr, String s) {
        data.setString(tag, vr, s);
    }

    public void save(String path) {
        try {
            File file = new File(path);
            DicomOutputStream dos = new DicomOutputStream(file);
            dos.writeDataset(fmi, data);
            dos.finish();
            dos.flush();
            dos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

// 构建唯一会话Id
    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
    }
//时间戳

    public static String getTimeStamp() {
        return System.currentTimeMillis() + "";
    }

    /**
     * 日期格式字符串转换成时间戳
     *
     * @param dateStr 字符串日期
     * @param format 如：yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String dateToStamp(String dateStr, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return String.valueOf(sdf.parse(dateStr).getTime() / 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 结合了MD5和SHA算法的，并加入密钥
     *
     * @param str 报文
     * @return
     */
    public static String getSHA256Str(String token, String str) {
        return Sha256.HMACSHA256(token, str);
        //  return DigestUtils.HMACSHA256(token, str);
    }

    /*
     * 获取文件大小
     * 通过FileChannel类来获取文件大小，这个方法通常结合输入流相关，
     * 因此可以用于文件网络传输时实时计算文件大小；
     * */
    public static long getFileSize(File file) {

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException ex) {
            PostTencent.ERRDCMOPERFLAG = 1;
            LOG.error("getFileSize错误1" + ex);
        }
        FileChannel fc = fis.getChannel();
        try {
            Long fileSize = fc.size();
            fis.close();
            return fileSize;
        } catch (IOException ex) {
            try {
                fis.close();
            } catch (IOException ex1) {
                PostTencent.ERRDCMOPERFLAG = 1;
                LOG.error("getFileSize()关闭文件流错误1 " + ex);
                java.util.logging.Logger.getLogger(DicomUtil.class.getName()).log(Level.SEVERE, null, ex1);
            }
            PostTencent.ERRDCMOPERFLAG = 1;
            LOG.error("getFileSize错误2" + ex);
        }
        return 0;
    }

    public static void main(String[] args) {
        File dicom = new File("C:\\aaa\\1.2.840.113704.1.111.2064.1516586961.450");
        InputStream fis;
        //fis = new FileInputStream(dicom);
        //DicomUtil dicomUtil = new DicomUtil(fis);
        DicomUtil dicomUtil = new DicomUtil(dicom);
        dicomUtil.setValueByTag(Tag.Modality, VR.CS, "*****");
        dicomUtil.setValueByTag(Tag.StudyDate, VR.DA, "***");
        dicomUtil.setValueByTag(Tag.PatientName, VR.PN, "病人1");
        dicomUtil.setValueByTag(Tag.PatientID, VR.LO, "病人ID");
        // fis = new FileInputStream(dicom);
        String value1 = dicomUtil.getValueByTag(Tag.SeriesInstanceUID);
        String value = dicomUtil.getValueByTag(Tag.SOPInstanceUID);
        System.out.println(dicomUtil.getValueByTag(Tag.StudyInstanceUID));
        System.out.println("value1=" + value1);
        System.out.println("value=" + value);

        //dicomUtil.save("C:\\Users\\zy\\Desktop\\ylzInfo\\0602_000004_3");
    }
}
